<template>
  <UpLoadExcel :onSuccess="onSuccess" />
</template>

<script>
import { addAllEmployees } from "@/api/employees";
export default {
  methods: {
    async onSuccess({ header, results }) {
      const userRelations = {
        手机号: "mobile",
        姓名: "username",
        入职日期: "timeOfEntry",
        转正日期: "correctionTime",
        工号: "workNumber",
      };
      let arr = [];
      results.forEach((item) => {
        // forEach找出每一项通过key替换中文key
        const userInfo = {};
        Object.keys(item).forEach((key) => {
          if (
            userRelations[key] === "timeOfEntry" ||
            userRelations[key] === "correctionTime"
          ) {
            //因为时间类型,需要new Date
            userInfo[userRelations[key]] = new Date(
              this.formatDate(item[key], "/")
            );

            return;
          }
          userInfo[userRelations[key]] = item[key];
        });
        arr.push(userInfo);
      });
      //处理过信息调用批量导入接口
      await addAllEmployees(arr);
      //回到之前页面
      this.$router.back();
    },
    //excel时间格式跟js时间不一样,调用这个函数处理
    formatDate(numb, format) {
      const time = new Date((numb - 1) * 24 * 3600000 + 1);
      time.setYear(time.getFullYear() - 70);
      const year = time.getFullYear() + "";
      const month = time.getMonth() + 1 + "";
      const date = time.getDate() - 1 + "";
      if (format && format.length === 1) {
        return year + format + month + format + date;
      }
      return (
        year +
        (month < 10 ? "0" + month : month) +
        (date < 10 ? "0" + date : date)
      );
    },
  },
};
</script>
